import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
// 安装插件
Vue.use(Vuex)

// 创建Store对象
const state = {
  cartList: []
}

const store = new Vuex.Store({
  state: {
    ...state,
    userList: [],
    currentUser: '',
    my: [0, 0, 0],
    error: '',
    collectGoods: []
  },
  mutations: {
    ...mutations,
    pay(state, info) {
      // 修改余额
      var tmp = state.my[0] - parseFloat(info.pay)
      Vue.set(state.my, 0, parseFloat(tmp.toFixed(2)))

      // 删除已购买商品
      var arr = state.cartList.filter((val) => {
        if(info.goods.indexOf(val) === -1) {
          return true
        }
        // console.log(info.goods.indexOf(val))
      })
      state.cartList = arr
      console.log(state.cartList)
    },
    login(state, username) {
      // console.log(state.userList)
      // var user = state.userList.find(item => {
      //   return item.username === info.username &&
      //          item.password === info.password
      // })
      // if(user) {
      //   // state.my[0] = 1000
        Vue.set(state.my, 0, 1000)
        state.currentUser = username
      //   state.currentUser = info
      //   // console.log('登录成功')
      // } else {
      //   state.error = '密码错误'
      // }
    },
    register(state, username) {
      // var user = state.userList.every(item => {
      //   return item.username !== info.username
      // })
      // if(user) {
      //   state.userList.push(info)
      //   state.currentUser = info
        Vue.set(state.my, 0, 1000)
        state.currentUser = username
      //   // state.my[0] = 1000
      //   // console.log('注册成功')
      // } else {
      //   state.error = '该用户名已存在'
      // }
    },
    resetError(state) {
      state.error = ''
    },
    addCollect(state, good) {
      var tmp = state.collectGoods.every(item => {
        return item.title !== good.title
      })
      if(tmp) {
        state.collectGoods.push(good)
      }
    }
  },
  actions: {
    ...actions,
  },
  getters: {
    ...getters,
  },
})

// 挂载
export default store

